//
//  CertificationSubmitController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/9/4.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Kingfisher
class CertificationSubmitController: WarningBaseController {
    
    fileprivate var _tableView: UITableView!
    fileprivate var tableView: UITableView {
        get {
            if _tableView != nil {
                return _tableView
            }
            _tableView = UITableView()
            _tableView.delegate = self
            _tableView.dataSource = self
            _tableView.backgroundColor = UIColor.clear
            _tableView.separatorStyle = .none
            _tableView.tableFooterView = UIView()
            _tableView.showsVerticalScrollIndicator = false
            
            regClass(_tableView, cell: UITableViewCell.self)
            regClass(_tableView, cell: CertificationAvatarCell.self)
            regClass(_tableView, cell: CertificationSubmitTextFieldCell.self)
            regClass(_tableView, cell: CertificationPhotoCell.self)
            
            return _tableView
        }
    }
    
    //当前controller是用来干嘛的
    enum ControllerStyle {
        case appeal         //提交申诉
        case certificate    //提交认证
        case beReturn       //提交后被退回，加载缓存
    }
    
    
    
    /***通用属性***/
    fileprivate var chooseGender: String?//页面显示的性别
    fileprivate var chooseProvinceAndCity:(ProviceModel,CityModel?)? //页面显示的省市
    fileprivate var username: String = "" //页面输入的用户名
    fileprivate var idcardString: String?
    fileprivate var avatarImage: UIImage? // 页面的头像
    fileprivate var positiveIdPhoto: UIImage? //身份证正面照
    fileprivate var reverseIdPhoto: UIImage? //身份证反面照
    
    //当前页面的类型
    var controllerStyle: ControllerStyle = ControllerStyle.certificate
    
    /***申诉***/
    
    //AppealPhoneNoController提交的表单
    var form:[String: Any]?

    init(_ style:ControllerStyle) {
        super.init(nibName: nil, bundle: nil)
        
        self.controllerStyle = style
    }
    
    init() {
        super.init(nibName: nil, bundle: nil)
        self.controllerStyle = ControllerStyle.certificate
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.mg_backgroundGray
        
//        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "点击", style: .done, target: self, action: #selector(doRightAction))
        
        self.view.addSubview(self.tableView)
        self.tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        self.displayViewByStyle()
    }
    
    //根据 controllerStyle 来显示不同的页面内容
    private func displayViewByStyle() {
        if self.controllerStyle == ControllerStyle.certificate {
            self.title = "认证资料"
//            self.navigationItem.hidesBackButton = true
        }
        
       if self.controllerStyle == .appeal {
            self.title = "提交申诉资料"
//            self.navigationItem.hidesBackButton = false
        }
        if self.controllerStyle == .beReturn {
            self.title = "认证资料"
            WWBeginLoadingWithStatus("正在获取资料")
            UserInfoModel.getMigrantWorkInfo(completionHandler: { (response) in
                if response.success {
                    if let model = response.value {
                        if let sex = model.sex {
                            if sex == .boy {
                                self.chooseGender = "男"
                            }
                            else {
                                self.chooseGender = "女"
                            }
                        }

                        let usernameCell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 1)) as! CertificationSubmitTextFieldCell
                        usernameCell.cellTextField.text = model.username ?? ""
                        self.username = model.username ?? ""
                        
                        let idcardCell = self.tableView.cellForRow(at: IndexPath.init(row: 2, section: 1)) as! CertificationSubmitTextFieldCell
                        idcardCell.cellTextField.text = model.idCard
                        self.idcardString = model.idCard
                        
                        if model.provinceModel != nil {
//                            let provinceAndCityCell = self.tableView.cellForRow(at: IndexPath.init(row: 2, section: 1)) as! CertificationSubmitTextFieldCell
                            self.chooseProvinceAndCity = (model.provinceModel!, model.cityModel)
                        }
                        
                        let avatarImageCell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 0)) as! CertificationAvatarCell
                        ImageDownloader.default.downloadImage(with: URL.init(string: ImageUrlPrefix + (model.photoUrl ?? ""))!, options: [], progressBlock: nil, completionHandler: { [unowned self](image, error, url, data) in
                            avatarImageCell.visiblePhoto = image
                            self.avatarImage = image
                        })

                        let idPhotoCell = self.tableView.cellForRow(at: IndexPath.init(row: 0, section: 2)) as! CertificationPhotoCell
                        ImageDownloader.default.downloadImage(with: URL.init(string: ImageUrlPrefix + (model.positiveIdCardUrl ?? ""))!, options: [], progressBlock: nil, completionHandler: { (image, error, url, data) in
                            idPhotoCell.positivePhoto = image
                            self.positiveIdPhoto = image
                        })
                        ImageDownloader.default.downloadImage(with: URL.init(string: ImageUrlPrefix + (model.reverseIdCardUrl ?? ""))!, options: [], progressBlock: nil, completionHandler: { (image, error, url, data) in
                            idPhotoCell.reversePhoto = image
                            self.reverseIdPhoto = image
                        })

                        self.tableView.reloadData()
                    }
                }
                else {
                    WWError(response.message)
                }
                WWEndLoading()
            })
        }
    }
    
    //点击底部蓝色按钮
    @objc func doSubmitAction() {
        guard self.avatarImage != nil else{
            WWInform("请上传头像")
            return
        }
        guard self.positiveIdPhoto != nil,self.reverseIdPhoto != nil else {
            WWInform("身份证正/反面都不能缺少")
            return
        }
       
        guard self.username.count > 0 else {
            WWError("用户名为空！")
            return
        }
        guard self.chooseGender != nil else {
            WWError("请选择性别")
            return
        }
        guard self.idcardString != nil,self.idcardString!.count > 0  else{
            WWError("请重新输入身份证号")
            return
        }
//        let index = self.idcardString!.index(self.idcardString!.endIndex, offsetBy: -1)
//        if self.idcardString!.substring(from: index) == "x" {
////            WWError("末尾的x必须是大写")
////            return
//        }
        
        guard Tool.checkIsIdentityCard(self.idcardString!) else {
            WWError("不是合法身份证")
            return
        }
        
        guard self.chooseProvinceAndCity != nil else {
            WWError("请选择省市")
            return
        }
        
        var avatarModel: ImageUploadModel?
        var idPhotoModels = [ImageUploadModel]()
        var guid: String?
        var orderNo: String?
        
        let dispatchGroup = DispatchGroup()
        
        WWBeginLoadingWithStatus("开始提交照片")
        
        dispatchGroup.enter()
        //上传头像
        ImageUploadModel.commitImage([self.avatarImage!]) { (response) in
            if response.success {
                avatarModel = response.value![0]
            }
            else {
                WWError(response.message)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.enter()
        ImageUploadModel.commitImage([self.positiveIdPhoto!,self.reverseIdPhoto!],isCertification: true) { (response) in
            if response.success {
                idPhotoModels = response.value!
            }
            else
            {
                WWError(response.message)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.enter()
        UserModel.getGuid { (response) in
            if response.success {
                guid = response.value
            }
            else {
                WWError("guid获取失败")
            }
            dispatchGroup.leave()
        }
        
        var orderConfigId: String!
        
        if self.controllerStyle == .appeal {
            orderConfigId = "28CA1B8E-9720-425E-935D-D097A2B298F4"
        }
        else {
            
            orderConfigId = "57ed0987-1c79-4c67-b6f8-23ec6304ba38"
        }
        
        UserModel.getOrderNo(orderConfigId: orderConfigId) { (response) in
            if response.success {
                orderNo = response.value
            }
            else {
                WWError("获取orderNo出错")
            }
        }
        
        dispatchGroup.notify(queue: DispatchQueue.main) {
            
            if self.controllerStyle == .appeal {
                
                WWBeginLoadingWithStatus("开始申诉")
            }
            else {
                WWBeginLoadingWithStatus("开始认证")
            }
            
            guard avatarModel != nil  else{
                WWError("头像上传出错")
                return
            }
            
            guard idPhotoModels.count == 2 else {
                WWError("身份证照上传出错")
                return
            }
            guard guid != nil else {
                return
            }
            guard orderNo != nil else {
                return
            }
            
            //当前页面是认证还是申诉
            if self.controllerStyle == .appeal {
                self.submitAppeal(guid!, orderNo: orderNo!, name: self.username, sex:self.chooseGender == "男" ? 0 : 1, iDCard: self.idcardString!, provinceAndCity: self.chooseProvinceAndCity!, avatar: avatarModel!, idPhotos: idPhotoModels)
            }
            else {
                self.submitCertificaiton(guid!, orderNo: orderNo!, name: self.username, sex: self.chooseGender == "男" ? 0 : 1, iDCard: self.idcardString!, provinceAndCity: self.chooseProvinceAndCity!, avatar:  avatarModel!, idPhotos: idPhotoModels)
            }

        }
    }
    
    private func checkCertificationStatus() {
        CertificationModel.checkCertificationStatus({ (response) in
            if response.success {
                WWUser.sharedInstance.ensureCertificationStatus(self)
            }
            else {
            }
        })
    }
    //提交认证
    func submitCertificaiton(_ guid: String, orderNo: String, name: String, sex: Int, iDCard: String, provinceAndCity: (ProviceModel, CityModel?), avatar:ImageUploadModel, idPhotos:[ImageUploadModel]) {
        CertificationModel.submitCertificationInfo(guid, orderNo: orderNo, name: name, sex: sex, iDCard: iDCard, userAdress: "", startTime: "", endTime: "", avatar: avatar, idPhotos: idPhotos, operate: "1", completionHandler: { (response) in
            if response.success {
                
                WWSuccess("成功")
                if self.controllerStyle == .certificate {
                    self.present(WWTabBarController(), animated: true, completion: nil)
                }
                if self.controllerStyle == .beReturn {
             self.navigationController?.popViewController(animated: true)
                    
                }
                self.checkCertificationStatus()
            }
            else
            {
                WWError(response.message)
            }
        })
    }
    
    //提交申诉
    func submitAppeal(_ guid: String, orderNo: String, name: String, sex: Int, iDCard: String, provinceAndCity: (ProviceModel, CityModel?), avatar:ImageUploadModel, idPhotos:[ImageUploadModel]) {
        guard idPhotos.count == 2 else {
            WWError("正面照出错")
            return
        }
        
        let provinceId = provinceAndCity.0.aId
        var cityId: String?
        if let cityModel = provinceAndCity.1 {
            cityId = cityModel.aId
        }
        else {
            cityId = ""
        }
        
        //origo
        let province = ["ID":provinceId]
        let city = ["ID":cityId]
        let origo = ["Province":province, "City":city]
        
        //头像Photo
        let photo = ["Name":avatar.name ?? "", "Path":avatar.url ?? "", "ID":avatar.aId ?? ""]
        
        //证件正反面照
        let idPhotoModel1 = idPhotos[0]
        let idPhotoModel2 = idPhotos[1]
        let iDCardDict1 = ["Name": idPhotoModel1.name ?? "", "Path": idPhotoModel1.url ?? "", "ID":idPhotoModel1.aId ?? ""]
        let iDCardDict2 = ["Name": idPhotoModel2.name ?? "", "Path": idPhotoModel2.url ?? "", "ID":idPhotoModel2.aId ?? ""]
        let iDCardSmartImageList = [iDCardDict1, iDCardDict2]
        
        var currentForm = ["Name": name, "Sex":sex, "IDCard":iDCard, "Origo":origo, "Photo":photo, "IDCardSmartImageList": iDCardSmartImageList, "OrderNo":orderNo] as [String : Any]
        
        if self.form != nil {
            for key in [String](self.form!.keys) {
                currentForm[key] = self.form![key]
            }
        }

        CertificationModel.submitAppeals(guid, form: currentForm) { (response) in
            if response.success {
                WWError("提交成功")
                
                WWUser.sharedInstance.loginOut()
                self.navigationController?.popToRootViewController(animated: true)
            }
            else {
                WWError(response.message)
            }
        }
        
    }
    
    func doRightAction() {
        let vc = BankCardAddController.init(BankCardAddController.BankCardAddControllerOption.certification)
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension CertificationSubmitController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return [1,4,1][section]
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 140
        }
        if indexPath.section == 2 {
            return 10 + 64 + 5 + 40
        }
        return 45
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = getCell(tableView, cell: CertificationAvatarCell.self, indexPath: indexPath)
            cell.photoSelectionHandler = {[unowned self](image) in
                self.avatarImage = image
            }
            return cell
        }
        if indexPath.section == 1 {
            let cell = getCell(tableView, cell: CertificationSubmitTextFieldCell.self, indexPath: indexPath)
            let images = ["Icon_用户名", "Icon_性别","Icon_身份证号码", "Icon_籍贯"]
            let placeholders = ["请输入您的真实姓名",  "请选择性别", "请输入您的身份证号码", "请选择您的籍贯"]
            cell.cellIcon.image = UIImage(named: images[indexPath.row])
            cell.cellTextField.placeholder = placeholders[indexPath.row]
            
            if indexPath.row == 1 || indexPath.row == 3{
                cell.isCellTextFieldCanEdit = false
                cell.accessoryType = .disclosureIndicator
                cell.cellTextField.isUserInteractionEnabled = false
            }
            if indexPath.row == 0 {
                cell.textFieldEditHandler = {[unowned self](result) in
                    self.username = result
                }
            }
            if indexPath.row == 1 {
                cell.cellTextField.text = self.chooseGender
            }
            if indexPath.row == 2 {
                cell.cellTextField.keyboardType = .asciiCapable
                cell.textFieldEditHandler = {[unowned self](result) in
                    self.idcardString = result
                }
            }
            if indexPath.row == 3 {
                if let tuple = self.chooseProvinceAndCity {
                    let province = tuple.0
                    let city = tuple.1
                    if city == nil {
                        cell.cellTextField.text = (province.name ?? "")
                    }
                    else {
                        cell.cellTextField.text = (province.name ?? "") + (city!.name ?? "")
                    }
                    
                }
            }
            return cell
        }
        if indexPath.section == 2 {
            let cell = getCell(tableView, cell: CertificationPhotoCell.self, indexPath: indexPath)
            cell.positivePhotoSelectedHandler = {[unowned self](image) in
                self.positiveIdPhoto = image

            }
            cell.reversePhotoSelectedHandler = {[unowned self](image) in
                self.reverseIdPhoto = image
            }
            return cell
        }
        
        let cell = getCell(tableView, cell: UITableViewCell.self, indexPath: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 1 {
            if indexPath.row == 1 {
                let vc = GenderChooseController()
                vc.selectionHandler = {[unowned self](result) in
                    self.chooseGender = result

                    tableView.reloadRows(at:[indexPath], with: .automatic)
                }
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if indexPath.row == 3 {
                let vc = AddressChooseController()
                vc.selectedHandler = {[unowned self](resultTuples) in
                    self.chooseProvinceAndCity = resultTuples
                    tableView.reloadRows(at: [indexPath], with: .automatic)
                }
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 2 || section == 1 {
            return 10
        }
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 2 {
           return 120
        }
        return 0.1
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 2 {
            let view = UIView()
            
            let button = UIButton()
            button.titleLabel?.font = wwFont_Medium(16)
            button.backgroundColor = UIColor.mg_blue
            button.layer.cornerRadius = 6
            button.layer.shadowColor = UIColor.black.cgColor
            button.layer.shadowOffset = CGSize(width: 1, height: 1)
            button.layer.shadowOpacity = 0.2
            view.addSubview(button)
            button.snp.makeConstraints { (make) in
                make.center.equalTo(view)
                make.width.equalTo(180)
                make.height.equalTo(40)
            }
            button.addTarget(self, action: #selector(doSubmitAction), for: .touchUpInside)
            
            if self.controllerStyle == .appeal {
                button.setTitle("申诉", for: .normal)
            }
            else {
                button.setTitle("认证", for: .normal)
            }
            
            return view

        }
        return nil
    }
}
